package com.yiqixue.orderservice.controller;

import com.yiqixue.orderservice.client.ProductServiceClient;
import com.yiqixue.orderservice.model.Order;
import com.yiqixue.orderservice.model.OrderItem;
import com.yiqixue.orderservice.model.Product;
import com.yiqixue.orderservice.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private ProductServiceClient productServiceClient;

    @GetMapping
    public List<Order> getAllOrders() {
        return orderRepository.findAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Order> getOrderById(@PathVariable Long id) {
        return orderRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<?> createOrder(@RequestBody Order order) {
        // 验证商品库存
        for (OrderItem item : order.getOrderItems()) {
            Product product = productServiceClient.getProductById(item.getProductId());
            if (product == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body("商品不存在: " + item.getProductId());
            }
            if (product.getStock() < item.getQuantity()) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body("商品库存不足: " + product.getName());
            }
        }

        // 设置订单日期和状态
        order.setOrderDate(LocalDateTime.now());
        order.setStatus("PENDING");

        // 计算订单总金额
        double totalAmount = 0.0;
        for (OrderItem item : order.getOrderItems()) {
            Product product = productServiceClient.getProductById(item.getProductId());
            item.setPrice(product.getPrice());
            totalAmount += product.getPrice() * item.getQuantity();
        }
        order.setTotalAmount(totalAmount);

        return ResponseEntity.ok(orderRepository.save(order));
    }

    @PutMapping("/{id}")
    public ResponseEntity<Order> updateOrder(@PathVariable Long id, @RequestBody Order orderDetails) {
        return orderRepository.findById(id)
                .map(existingOrder -> {
                    existingOrder.setCustomerId(orderDetails.getCustomerId());
                    existingOrder.setStatus(orderDetails.getStatus());
                    existingOrder.setTotalAmount(orderDetails.getTotalAmount());
                    return ResponseEntity.ok(orderRepository.save(existingOrder));
                })
                .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteOrder(@PathVariable Long id) {
        return orderRepository.findById(id)
                .map(order -> {
                    orderRepository.delete(order);
                    return ResponseEntity.ok().build();
                })
                .orElse(ResponseEntity.notFound().build());
    }
} 